import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:http/http.dart' as http;

class DioUploadTest extends StatefulWidget {
  @override
  _DioUploadTestState createState() => _DioUploadTestState();
}

class _DioUploadTestState extends State<DioUploadTest> {
  String _responseText="";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('文件上传Demo'),
      ),
      body: Center(
        child: Text(_responseText),
      ),
    );
  }

  ///
  /// 单个文件上传
  ///
  static void uploadSingleFile({
    http.MultipartFile file, 
    Function successCallback,
    Function failCallback,
  }) async {
    String url = "http://39.108.246.130/api/file/upload";
    Map<String, http.MultipartFile> files = <String, http.MultipartFile> {
      "file": file,
    };

    Map<String, String> headers = <String, String>{
      "Content-type": "multipart/form-data; charset=utf-8"
    };
    headers.addAll({"Authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIyOSIsIm1lbSI6IumZiOeOieW8uiIsImNyZWF0ZWQiOjE1MzY4NjcyMTg5ODMsImV4cCI6MTUzODMzODQ0N30.tbqw_lwKknpAC_AO8mmVxiFKdwDrOX17pUnc3jkpeyNzlzCjfM0vKuftzO7xitjd4-DhaqrEVMoI_SB9zTL5Mw"});

    try {
      http.Response res = await http.post(url, body: files, headers: headers);
      print("post response: ${res.body}");
      print("文件上传成功");
    } catch (e) {
      print("文件上传失败");
    }
  }

  uploadFile() {
    FormData formData = new FormData.from({
      "name": "wendux",
      "age": 25,
      // "file1": new UploadFileInfo(new File("./upload.txt"), "upload1.txt"),
      // "file2": new UploadFileInfo(new File("./upload.txt"), "upload2.txt"),
      // Pass multiple files within an Array
      "files": [
        new UploadFileInfo(new File("./assets/upload.txt"), "upload.txt"),
        new UploadFileInfo(new File("./assets/upload.txt"), "upload.txt")
      ]
    });

    var dio = new Dio();
    dio.onHttpClientCreate = (HttpClient client) {
      client.idleTimeout = new Duration(seconds: 0);
    };

    dio.post("http://39.108.246.130/api/file/upload", data: formData).then((Response response) {
        setState(() {
          _responseText =
              "statusCode: ${response.statusCode}, download succeed!";
        });
    });
  }
}
